<?php
/**
 *   Joomdiet - administrator/components/models/foodcategories.php
 *   Author: Juan Dapena Paz (juan@bittingbits.com)
 *   Copyright (C) 2010 Bitting Bits S.L.
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

defined('_JEXEC') or die('Restricted access');

 
jimport('joomla.application.component.model');
class BbitsdModelItems extends JModel
{
    var $_data = array();
    var $_item; 
    var $_pagination;
	var $_types=null;
    
    function __construct()
    {
        parent::__construct();
        
        global $mainframe, $option;
        
        try {
            $array = JRequest::getVar('cid', 0, '', 'array');
            $this->setId((int)$array[0]);
        } catch (Exception $e) {
            // do nothing
        }

		
        // loading pagination support
        $limit = $mainframe->getUserStateFromRequest('global.list.limit',
                                                     'limit',
                                                     $mainframe->getCfg('list_limit'),
                                                     'int');
        $limitstart = JRequest::getVar('limitstart', 0, '', 'int');
        $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
        
        $this->setState('limit', $limit);
        $this->setState('limitstart', $limitstart);




	
}



	function _buildQuery()
    {
    $query = ' SELECT *  FROM #__bbitsd_items '. $this->_buildQueryWhere().$this->_buildQueryOrderBy();

       return $query;
	}
 	
 	function _buildQueryWhere()
    {
       global $mainframe, $option;
       // get the filter published state value
       $filter_state = $mainframe->getUserStateFromRequest($option.'filter_state','filter_state');
       $filter_catid = $mainframe->getUserStateFromRequest($option.'filter_catid', 'filter_catid');
       $filter_typeid = $mainframe->getUserStateFromRequest($option.'filter_typeid', 'filter_typeid');

       // prepare the WHERE clause
	   $where = array();
       // Determine published state
       if ($filter_state == 'P')
       {
           $where[] = 'published = 1';
       }
       
       elseif ($filter_state == 'U')
       {
           $where[] = 'published = 0';
       }
       
       // Determine category ID
    	if ($filter_catid = (int)$filter_catid)
    	{
        $where[] = 'country = '.$filter_catid;
    	}
       
       	// Determine category ID
    	if ($filter_typeid = (int)$filter_typeid)
    	{
        $where[] = 'type = '.$filter_typeid;
    	}

       // return the WHERE clause
  	    
  	    return (count($where)) ? ' WHERE '.implode(' AND ', $where) : '';                
     
    }
    
    function _buildQueryOrderBy()
    {
		global $mainframe, $option;
       // Array of allowable order fields
       $orders = array('title', 'published', 'id', 'hits','ordering','type');
       // get the order field and direction
       $filter_order = $mainframe->getUserStateFromRequest($option.'filter_order','filter_order', 'published');
	   $filter_order_Dir = $mainframe->getUserStateFromRequest($option.'filter_order_Dir','filter_order_Dir', 'asc');

       // validate the order direction, must be ASC or DESC

        if ($filter_order_Dir != 'asc' && $filter_order_Dir != 'desc')
        {
        
           $filter_order_Dir = 'asc';
        }

	    // if order column is unknown use the default
	    if (!in_array($filter_order, $orders))
	    {
	        $filter_order = 'id';
	    }

	    // return the ORDER BY clause
	    return ' ORDER BY '.$filter_order.' '.$filter_order_Dir;   

    }
    
    
    function setId($id)
    {
        $this->_id = $id;
        $this->_variable = null;
    }
    
    function getData()
    {
    

        if (empty($this->_data)) {
            $query = $this->_buildQuery();
            if (empty($this->_pagination)) {
                $this->_data = $this->_getList($query);
            } else {
                $this->_data = $this->_getList($query, 
                                               $this->getState('limitstart'),
                                               $this->getState('limit'));
            }
            if (empty($this->_data)) $this->_data = array();
        }

        return $this->_data;
    }

   	function getItem1()
    {
        if ($this->_loadItem()) {
        } else $this->_initItem();
        
        return $this->_item;
    }
    
    function getItemyById($id) {
        $query = 'SELECT * FROM #__bbitsd_items WHERE id='.$id;
        $this->_db->setQuery($query);
        return $this->_db->loadObject();
    }
    
    function _loadItem()
    {
        if (empty($this->_item))
        {
            $query = 'SELECT * FROM #__bbitsd_items WHERE id='.$this->_id;
            $this->_db->setQuery($query);
            $this->_item = $this->_db->loadObject();
            
            return (boolean) $this->_item;
        }
    }
    
    function _initItem()
    {
        if (empty($this->_item)) {
            $item = new stdClass();
            $item->id = 0;
            $item->title = null;
            $item->country = 0;
            $item->description = null;
            $item->direction = null;
            $item->image = null;
            $item->type = 0;
            $item->phone = null;
            $item->fax = null;
            $item->email = null;
            $item->url = null;
            $item->checked_out_time = '0000-00-00 00:00:00';
			$item->ordering = 0;
			$item->published = 1;


            
            $this->_item = $item;
            return (boolean) $this->_item;
        }
        
        return true;
    }
    

    function delete($id)
    {
            // deleting food
            $query = 'DELETE FROM #__bbitsd_items WHERE id='.$id;
            $this->_db->setQuery($query);
            $this->_db->query();
            return true;
    }
    
     function store() 
    {
    	jimport( 'joomla.filesystem.file' );
        $this->getItem1();
      
        $this->_item->title = JRequest::getVar('item_title');
        $this->_item->id = JRequest::getVar('item_id');
        $this->_item->description = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWHTML);
         
        $deleteim = JRequest::getVar('delete_im');
        $currentim = JRequest::getVar('current_image');
        $uploadFile = JRequest::getVar('uploadFile',null, 'FILES', 'ARRAY');


       if(($deleteim==1) AND ($currentim!='')){
       
       	$filePath = JPATH_COMPONENT.DS.'assets/uploads/'.$currentim;
       	$fileDeleted = JFile::delete($filePath);
       	$query = 'UPDATE #__bbitsd_items SET image="" WHERE id='.$this->_item->id;
        $this->_db->setQuery($query);
        $this->_db->query();
       }
       
       if(($uploadFile['size']>1) AND ($currentim!='')){
       
       	$filePath = JPATH_COMPONENT.DS.'assets/uploads/'.$currentim;
       	$fileDeleted = JFile::delete($filePath);        
                    	
       }
       

if($uploadFile['size']>1):
        if(!is_array($uploadFile))
        {
        	echo "Error uploading file1";
        }
        
        elseif($uploadFile['error'] || $uploadFile['size']<1)
        {
        	echo "Error uploading file2";
        }
		
		elseif(!is_uploaded_file($uploadFile['tmp_name']))
		{
			echo "Error uploading file3";
		}
		
		else{
		
		$config = & JFactory::getConfig();		
		$path = JPATH_BASE."/components/com_bbitsd/assets/uploads";

		$filename = uniqid().$uploadFile['name'];
		$fileDestination = $path.DS.JFile::getName($filename);
	        
        $uploaded = JFile::upload($uploadFile['tmp_name'], $fileDestination);


       }
endif;       
        $this->_item->country = JRequest::getVar('country_id');
        $this->_item->direction = JRequest::getVar('direction');
        $this->_item->image = JRequest::getVar('image');
        $this->_item->type = JRequest::getVar('type_id');
        $this->_item->phone = JRequest::getVar('phone');
        $this->_item->fax = JRequest::getVar('fax');
        $this->_item->email = JRequest::getVar('email');
        $this->_item->url = JRequest::getVar('url');
        $this->_item->checked_out_time = JRequest::getVar('checked_out_time');
        $this->_item->published = JRequest::getVar('published');

        if ($this->_item->id==0) {

        if(isset($filename)):

        
            $query = 'INSERT INTO #__bbitsd_items'.
                ' (title,ordering,country,description,direction,type,phone,fax,email,url,image,checked_out_time,published) VALUES'.
                ' ("'.$this->_item->title.'","'.$this->_item->ordering.'","'.$this->_item->country.'","'.mysql_escape_string($this->_item->description).'","'.$this->_item->direction.'","'.$this->_item->type.'","'.$this->_item->phone.'","'.$this->_item->fax.'","'.$this->_item->email.'","'.$this->_item->url.'","'.$filename.'","'.$this->_item->checked_out_time.'","'.$this->_item->published.'")';
         
        else:

        	$query = 'INSERT INTO #__bbitsd_items'.
                ' (title,ordering,country,description,direction,type,phone,fax,email,url,checked_out_time,published) VALUES'.
                ' ("'.$this->_item->title.'","'.$this->_item->ordering.'","'.$this->_item->country.'","'.mysql_escape_string($this->_item->description).'","'.$this->_item->direction.'","'.$this->_item->type.'","'.$this->_item->phone.'","'.$this->_item->fax.'","'.$this->_item->email.'","'.$this->_item->url.'","'.$this->_item->checked_out_time.'","'.$this->_item->published.'")';
 
        endif; 
         
        } else {
        
        if(isset($filename)):
        
            $query = 'UPDATE #__bbitsd_items '.
                ' SET title="'.$this->_item->title.'", ordering="'.$this->_item->ordering.'", published="'.$this->_item->published.'", country="'.$this->_item->country.'", checked_out_time="'.$this->_item->checked_out_time.'", description="'.mysql_escape_string($this->_item->description).'", direction="'.$this->_item->direction.'", type="'.$this->_item->type.'", phone="'.$this->_item->phone.'", fax="'.$this->_item->fax.'", image="'.$filename.'", email="'.$this->_item->email.'", url="'.$this->_item->url.'"'.
                ' WHERE id='.$this->_item->id;
                
         else:
         	
         	$query = 'UPDATE #__bbitsd_items '.
                ' SET title="'.$this->_item->title.'", ordering="'.$this->_item->ordering.'", published="'.$this->_item->published.'", checked_out_time="'.$this->_item->checked_out_time.'", country="'.$this->_item->country.'",description="'.mysql_escape_string($this->_item->description).'", direction="'.$this->_item->direction.'", type="'.$this->_item->type.'", phone="'.$this->_item->phone.'", fax="'.$this->_item->fax.'", email="'.$this->_item->email.'", url="'.$this->_item->url.'"'.
                ' WHERE id='.$this->_item->id;
         
         endif;
        }
        
        $this->_db->setQuery($query);
        $this->_db->query();
        
        if (!$this->_item->id) {
            return $this->_db->insertid();
        } else return $this->_item->id;
    }
    

    function getPagination()
    {
        if (empty($this->_pagination)) {
            jimport('joomla.html.pagination');
            $this->_pagination = new JPagination($this->getTotal(),
                                                 $this->getState('limitstart'),
                                                 $this->getState('limit'));
        }
        
        return $this->_pagination;
    }
    
        function getTotal()
    {
        if (empty($this->_total)) {
            $query = $this->_buildQuery();
            $this->_total = $this->_getListCount($query);
        }
        return $this->_total;
    }
    function getModel()
    {
        return $this;
    }
    
    
    function publishList($cid = array(), $publish = 1) {
         $user  =& JFactory::getUser();
         if (count( $cid ))
         {
             JArrayHelper::toInteger($cid);
             $cids = implode( ',', $cid );
             $query = 'UPDATE #__bbitsd_items'
                   . ' SET published  = '.(int) $publish
                   . ' WHERE id IN ( '.$cids.' )'
                 . ' AND ( checked_out = 0 OR ( checked_out = '.(int)
$user->get('id').' )' ;
                  $this->_db->setQuery( $query );
                if (!$this->_db->query()) {
                    $this->setError($this->_db->getErrorMsg());
                    return false;
                 }
           }
           return true;
 	} 
    
    
   }
?>
